package com.inkyi.assistant.core.scheduling;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.CronTask;
import org.springframework.scheduling.config.ScheduledTask;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.config.Task;

import java.util.Objects;
import java.util.Set;

@Slf4j
@Configuration
@EnableScheduling
public class InkScheduledTaskUtils implements SchedulingConfigurer {

    private static ScheduledTaskRegistrar scheduledTaskRegistrar;

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        log.info("定时任务注册器：{}", scheduledTaskRegistrar);
        InkScheduledTaskUtils.scheduledTaskRegistrar = scheduledTaskRegistrar;
    }

    /**
     * 添加计划任务
     *
     * @param inkTask 墨水任务
     */
    public static void addScheduledTask(InkCornTask inkTask) {
        if(inkTask == null || inkTask.getTaskId() == null || inkTask.getTaskId().isEmpty()
                || inkTask.getExpression() == null || inkTask.getExpression().isEmpty()) {
            return;
        }

        cancelScheduledTask(inkTask.getTaskId());
        scheduledTaskRegistrar.addCronTask(inkTask, inkTask.getExpression());
        scheduledTaskRegistrar.afterPropertiesSet();
    }

    /**
     * 取消计划任务
     *
     * @param taskId 任务id
     * @return boolean
     */
    public static boolean cancelScheduledTask(String taskId) {
        boolean cancel = false;
        ScheduledTask scheduledTask = findScheduledTask(taskId);
        if (Objects.nonNull(scheduledTask)) {
            scheduledTask.cancel();
        }
        return cancel;
    }

    /**
     * 查找计划任务
     *
     * @param taskId 任务id
     * @return {@link ScheduledTask }
     */
    public static ScheduledTask findScheduledTask(String taskId) {
        Set<ScheduledTask> scheduledTasks = scheduledTaskRegistrar.getScheduledTasks();
        for (ScheduledTask scheduledTask : scheduledTasks) {
            Task task = scheduledTask.getTask();
            if (task instanceof CronTask cronTask) {
                Runnable runnable = cronTask.getRunnable();
                if (runnable instanceof InkCornTask inkCornTask) {
                    if (Objects.equals(inkCornTask.getTaskId(), taskId)) {
                        return scheduledTask;
                    }
                }
            }
        }
        return null;
    }

}
